package com.shwread.android.ui.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.RegionContentView;
import com.shwread.android.ui.widget.RegionContentView.RegionContentViewListener;
import com.shwread.android.ui.widget.RegionModelView;
import com.shwread.android.ui.widget.RegionModelView.OnModuleSelectedListener;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryEnterpriseZoneBannerAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;


/**
 * 新的企业专区页面
 */
public class NewEnterprisePage extends AbstractUIPage<MainActivity> implements OnClickListener, OnModuleSelectedListener {
    private static NewEnterprisePage instance;
    private TextView tvTitle;
    private ImageView ivPersion;

    private HashMap<Integer, View> views;
    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private List<BannerInfo> banners;
    private ViewPagerAdapter pagerAdapter;
    private static Rect ViewPagerRect;

    private View loadingView;
    private ImageView loadingImg, gotoTopImg;
    private AnimationDrawable animationDrawable;
    /**
     * 判断最后一次数据加载是否成功，不成功的话每次进入此页面需要显示加载动画
     */
    private boolean isLastSuccess = false;
    public static boolean netAvilible = true;
    private View titleView;
    private PullToRefreshScrollView contentView;

    private QryEnterpriseZoneBannerAction bannerAction;

    //added by zouqp
    private LinearLayout ll_newenterprise_contentview;
    private RegionModelView modelView;
    private RegionContentView contentItemView;
    private long currentModelId = -1;

    public static NewEnterprisePage getInstance(MainActivity bActivity) {
        if (instance == null) {
            instance = new NewEnterprisePage(bActivity);
        } else {
            instance.setActivity(bActivity);
        }
        return instance;
    }

    public NewEnterprisePage(MainActivity t) {
        super(t);
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) {
            return curMyView;
        }
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.new_enterprise, null);

        initView();
        setListener();
        initGuide();
        return curMyView;
    }

    @SuppressLint("UseSparseArrays")
    void initView() {
        banners = new ArrayList<>();
        views = new HashMap<>();
        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("小镇动态");
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.VISIBLE);//用户登录按钮设置成可见
        //lv = (ListView) curMyView.findViewById(R.id.new_enterprise_listview);
        ll_newenterprise_contentview = (LinearLayout) curMyView.findViewById(R.id.ll_newenterprise_contentview);
        loadingView = curMyView.findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);

        titleView = curMyView.findViewById(R.id.common_title_layout);

        gotoTopImg = (ImageView) curMyView.findViewById(R.id.new_enterprise_goto_top);

        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.new_enterprise_view);

        PullToRefreshUtil.initLabel(context, contentView);

        vpPager = (QYViewPager) curMyView.findViewById(R.id.enterprise_head_pager);
        vgPoints = (ViewGroup) curMyView.findViewById(R.id.enterprise_head_points);

        // 获取ViewPager在屏幕的位置
        final ViewTreeObserver observer = vpPager.getViewTreeObserver();
        OnGlobalLayoutListener global = new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (ViewPagerRect == null) {
                    ViewPagerRect = new Rect();
                    vpPager.getGlobalVisibleRect(ViewPagerRect);
                }
            }
        };
        observer.addOnGlobalLayoutListener(global);
    }

    void setListener() {
        ivPersion.setOnClickListener(this);
        gotoTopImg.setOnClickListener(this);
        titleView.setOnClickListener(this);
        vpPager.setOnPageChangeListener(new PagerChangeListener());

        pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);

        contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) { //下拉刷新
                    modelView.setCanSwitchModule(false);
                    refresh();
                } else if (contentView.isFooterShown()) { //上拉加载
                    loadMore();
                }
            }
        });
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        //TODO
        if (currentModelId != -1) {
            contentItemView.getModelData(currentModelId, 1);
        } else {
            contentView.onRefreshComplete();
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (contentItemView.getDataSize() == 0) {
            PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
        } else {
            if (contentItemView.getHasMore()) {
                //加载下一页
                contentItemView.getNextPage();
                return;
            } else if (contentItemView.isGotMaxSize()) {
                //已经达到了最大条数，
                PullToRefreshUtil.setLoadLabel(contentView, "已经达到了最大条数");
            } else {
                //没有更多了， 所以不再加载下一页
                PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
            }
        }
        contentView.onRefreshComplete();
    }

    /******************************* Banner start *********************************/
    /**
     * 获取企业专区Banner数据
     */
    private class GetBannerAction extends BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            List<BannerInfo> temp = (List<BannerInfo>) obj;
            banners.clear();
            if (temp.size() <= 1) {
                banners = temp;
            } else {
                banners.add(temp.get(temp.size() - 1));
                banners.addAll(temp);
                banners.add(temp.get(0));
            }
            temp = null;
            System.out.println("企业专区banner obj:" + banners.toString());
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (banners.size() > 0) {
                        pagerAdapter.setData(banners);
                        initBannerView();
                    } else {
                        //lv.removeHeaderView(bannerView);
                    }
                    updateLoadingView(1);
                    gotoTop();
                }
            });
            bannerAction = null;
        }

        @Override
        protected void onError() {
            super.onError();
            bActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    updateLoadingView(-1);
                }
            });
            bannerAction = null;
            isLastSuccess = false;
        }
    }

    void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++) {
            View view = bActivity.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        pagerAdapter.notifyDataSetChanged();
        startScroll();
    }

    Runnable action = new Runnable() {
        @Override
        public void run() {
            int currentItem = vpPager.getCurrentItem();
            currentItem++;
            if (currentItem >= pagerAdapter.getCount()) {
                currentItem = 0;
            }
            vpPager.setCurrentItem(currentItem);
        }
    };

    private void startScroll() {
        if (banners.size() <= 1) {
            return;
        }
        vpPager.removeCallbacks(action);
        vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
    }

    @Override
    public void dispose() {
        isLastSuccess = false;
        if (null != banners) {
            banners.removeAll(banners);
        }
        super.dispose();
        if (null != vpPager && null != action) {
            vpPager.removeCallbacks(action);
        }
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++) {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1) {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            } else {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    // TODO 点击Banner
    private void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:

                break;
            case BannerInfo.TYPE_BOOKS:

                break;
            case BannerInfo.TYPE_BOOKSURL:
                bActivity.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
                bActivity.goWebViewActivity(info);
                break;
        }
    }

    private class PagerChangeListener implements OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
            startScroll();
        }
    }

    /********************************
     * Banner end
     *********************************/

    @Override
    public int enter(IUIPage<?> arg0) {
        showGuide();
        if (NetworkUtil.isNetAvailable(bActivity)) {
            if (!isLastSuccess) {
                updateLoadingView(0);
            }
//			if (!netAvilible) modelView.getModules();
            if (bannerAction == null) {
//                bannerAction = new QryEnterpriseZoneBannerAction(bActivity, new GetBannerAction());
//                bannerAction.start();
                NewActionHelp.qryEnterpriseZoneBanner(bActivity, new ObjectHttpResponseHandler<List<BannerInfo>>() {
                    @Override
                    public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                        Log.e("111111fail", "qryEnterpriseZoneBanner" + s);
                        bActivity.getUIHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                updateLoadingView(-1);
                            }
                        });
                        isLastSuccess = false;
                    }

                    @Override
                    public void onSuccess(int i, Header[] headers, List<BannerInfo> bannerInfos, String s) {
                        Log.e("111111OK", "qryEnterpriseZoneBanner" + s);
                        banners.clear();
                        if (bannerInfos.size() <= 1) {
                            banners = bannerInfos;
                        } else {
                            banners.add(bannerInfos.get(bannerInfos.size() - 1));
                            banners.addAll(bannerInfos);
                            banners.add(bannerInfos.get(0));
                        }
                        bActivity.getUIHandler().post(new Runnable() {
                            @Override
                            public void run() {
                                if (banners.size() > 0) {
                                    pagerAdapter.setData(banners);
                                    initBannerView();
                                } else {
                                    //lv.removeHeaderView(bannerView);
                                }
                                updateLoadingView(1);
                                gotoTop();
                            }
                        });
                    }

                    @Override
                    public Type getType() {
                        return new TypeToken<List<BannerInfo>>() {
                        }.getType();
                    }
                });
            }
            //增加模块视图
            if (modelView == null) {
                modelView = new RegionModelView(context);
                modelView.setOnModuleSelectedListener(this);
                modelView.setBaseActivity(bActivity);
                ll_newenterprise_contentview.addView(modelView);
            }

            //增加内容项视图
            if (contentItemView == null) {
                contentItemView = new RegionContentView(context);
                contentItemView.setBaseActivity(bActivity);
                contentItemView.setRegionContentViewListener(new RegionContentViewListener() {
                    @Override
                    public void OnLoadDataCompleted(int flag) {
                        modelView.setCanSwitchModule(true);
                        if (flag == 1) { //首次装载
                            contentView.onRefreshComplete();
                        } else if (flag == 2) {//装载更多
                            contentView.onRefreshComplete();
                        }
                    }
                });
                ll_newenterprise_contentview.addView(contentItemView);
                modelView.getModules();
            }
        } else {
            new NoNetDialog(bActivity).show();
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.PAGE_ONRESUME_CODE:
                if (currentModelId != -1) {
                    contentItemView.getModelData(currentModelId, 1);
                }
                break;
            case BaseBusinessActivity.COMMENTS_REQUEST_CODE:
                //contentItemView.getModelData(currentModelId, 1);
                contentItemView.updateTheCommentsCount();
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void moduleSelected(long modelId) {
        currentModelId = modelId;
        PullToRefreshUtil.initLabel(context, contentView);
        contentItemView.getModelData(modelId, 2);

        //FIXME 测试用
        //		Intent intent = new Intent("com.shwread.android.qysw.ACTION.RECEIVE_CUSTOM_SYSTEM_NOTIFICATION");
        //		CustomSystemNotification noti = new CustomSystemNotification();
        //		noti.setContent("云信测试信息");
        //		noti.setTime(System.currentTimeMillis());
        //		intent.putExtra(NimIntent.EXTRA_BROADCAST_MSG, noti);
        //		bActivity.sendBroadcast(intent);

        //		Intent intent= new Intent(bActivity, BubbleActivity.class);
        //		intent.putExtra("Running", true);
        //		intent.putExtra(DefaultConsts.message_id, "477");
        //		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //		bActivity.startActivity(intent);

    }

    /**
     * 读取模块数据时的错误处理
     */
    @Override
    public void onError(String error) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_persion:
                bActivity.goPersonalActivity();
                break;
            case R.id.new_enterprise_goto_top:
                gotoTop();
                break;
            case R.id.common_title_layout:
                titleDoubleClick();
                break;
        }
    }

    private int clickCount;
    private long preClickTime;
    /**
     * 双击有效时间500毫秒
     */
    private final int defalultValue = 500;

    /**
     * 标题栏双击，回到顶部
     */
    private void titleDoubleClick() {
        if (clickCount == 0) {
            preClickTime = System.currentTimeMillis();
            clickCount++;
        } else if (clickCount == 1) {
            if ((System.currentTimeMillis() - preClickTime) < defalultValue) {
                gotoTop();
            }
            clickCount = 0;
            preClickTime = 0;
        } else {
            clickCount = 0;
            preClickTime = 0;
        }
    }

    /**
     * 首次进入page加载动画
     *
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                contentView.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 回到顶部
     */
    private void gotoTop() {
        contentItemView.post(new Runnable() {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    private GuideDialog dialog;
    private boolean showHelp;
    private QyreaderPerferencesUtil util;

    private void initGuide() {
        util = QyreaderPerferencesUtil.getInstance(bActivity, DefaultConsts.FIRST_TAG);
        dialog = new GuideDialog(bActivity, R.layout.enterprise_page_firstin);
    }

    private void showGuide() {
        showHelp = util.getShowEnterpriseHelp();
        if (showHelp) {
            if (null != dialog && !dialog.isShowing()) {
                dialog.show();
            }
            util.setShowEnterpriseHelp(false);
        }
    }
}
